App.controller('bookingPassengerController', ['$rootScope', '$scope', '$state', '$window', 'Page',function($rootScope, $scope, $state, $window, Page) {
	if(!$scope.booking || !$scope.booking.line || !$scope.booking.line.stops){
		return false;
	}
	
	
	$scope.booking.line.onStops = []; 
	$scope.booking.line.offStops = []; 
	$($scope.booking.line.stops).each(function(idx, stop){
		if(stop.stopType == '1'){
			$scope.booking.line.onStops.push(stop);
		}else if(stop.stopType == '2'){
			$scope.booking.line.offStops.push(stop);
		}
	});
	
	
	$scope.addPassenger = function(passenger){
		passenger = passenger || {};
		$scope.booking.passengers.push({
			name : passenger.name || '',
			phone : passenger.phone || '',
			onStopId : (function(){
				var stopId = '';
				$($scope.booking.line.stops).each(function(idx, stop){
					if(stop.stopType == '1'){
						stopId = stop.stopId;
						return false;
					}
				});
				return stopId;
			})(),
			offStopId : ''
		});
	};
	
	$scope.removePassenger = function(passenger,idx){
		if(!$scope.booking.passengers || $scope.booking.passengers.length <= 1){
			Page.alert("至少保留一位乘车!");
			return;
		}
		Page.confirm("确认取消该名乘客?",function(){
			$scope.$apply(function() {  
				$scope.booking.passengers.splice(idx,1);
			});
		});
	};
	
	if(!$scope.booking.passengers){
		$scope.booking.passengers = [];
		$scope.addPassenger({
			name : $rootScope.user ? $rootScope.user.realName : '',
			phone : $rootScope.user ? $rootScope.user.phone : ''
		});
	}
	
	
	$scope.bookingNextStep = function() {
		if($scope.booking.passengers.length == 0){
			Page.alert("请至少填写一位乘车信息!");
			return false;
		}
		
		var valid = true;
		
		var phoneRegex = /^1[3|4|5|7|8]\d{9}$/;
		$($scope.booking.passengers).each(function(idx, passenger){
			if($scope.booking.line.lineType == '1' && passenger.name == ''){//定制公交
				Page.alert("乘客姓名不能为空!");
				valid = false;
				return false;
			}else if($scope.booking.line.lineType == '2' && passenger.name == ''){//职工专线
				Page.alert("职工编号不能为空!");
				valid = false;
				return false;
			}else if(passenger.name == ''){
				Page.alert("乘客不能为空!");
				valid = false;
				return false;
			}

			if(passenger.phone == ''){
				Page.alert("手机号码不能为空!");
				valid = false;
				return false;
			}else if(!phoneRegex.test(passenger.phone)){
				Page.alert("手机号码格式不正确!");
				valid = false;
				return false;
			}
			if(passenger.onStopId == ''){
				Page.alert("上车地点不能为空!");
				valid = false;
				return false;
			}

		});

		if(isRepeatPhone($scope.booking.passengers)) {
			Page.notice("乘客的电话号码重复!");
			return;
		}

		if(valid){
			$state.go('booking.confirm');
		}
	};

	function isRepeatPhone(passengers){
		var hash = {};
		for(var i in passengers) {
			if(hash[passengers[i].phone])
				return true;
			hash[passengers[i].phone] = true;
		}
		return false;
	}
	
	$scope.bookingPreStep = function() {
		$state.go('booking.date');
	};
	
}]);